package com.baiyang.app.ui.mine.goods;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.baiyang.app.MyApp;
import com.baiyang.app.R;
import com.baiyang.app.databinding.ActivityGoodsBinding;
import com.baiyang.app.model.Goods;
import com.baiyang.app.model.User;
import com.baiyang.app.tool.AlertUtil;
import com.baiyang.app.tool.DataTool;
import com.baiyang.app.tool.LoadDataScrollController;
import com.baiyang.app.tool.MyAdapter;
import com.baiyang.app.ui.mine.exchange.RecordExchangeActivity;
import com.baiyang.app.ui.mine.exchange.RecordExchangeService;
import com.baiyang.app.ui.mine.exchange.RecordExchangeViewModel;

import java.util.ArrayList;

public class GoodsActivity extends AppCompatActivity implements LoadDataScrollController.OnRecycleRefreshListener{

    private ActivityGoodsBinding binding;
    private GoodsViewModel viewModel;
    private GoodsService service;
    private User user;
    private int pageOn = 1 ;

    private RecyclerView recyclerView;
    private SwipeRefreshLayout mSwipeRefresh;
    private LoadDataScrollController mController;
    private MyAdapter<Goods> myAdapter ;
    private ProgressDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_goods);
        viewModel = new ViewModelProvider(this).get(GoodsViewModel.class);
        service = new GoodsService(getApplicationContext(),viewModel);
        user = MyApp.getInstance().getUser();
        recyclerView = binding.recyclerView;
        mSwipeRefresh = binding.refresh;
        this.mController = new LoadDataScrollController(this);
        myAdapter = new MyAdapter<Goods>(new ArrayList<>(),R.layout.item_good) {
            @Override
            public void bindView(ViewHolder holder, Goods obj) {
                holder.setPic(R.id.pic,obj.getPic());
                holder.setText(R.id.name,obj.getGoodName());
                if(obj.getGoodType().equals("0")){
                    holder.setText(R.id.type,"虚拟");
                }else{
                    holder.setText(R.id.type,"实物");
                }
                holder.setText(R.id.requiredNum,String.valueOf(obj.getRequiredNum()));
                holder.setText(R.id.num,String.valueOf(obj.getGoodNum()));
                holder.setText(R.id.laveNum,String.valueOf(obj.getLaveNum()));
                holder.setmOnItemClickListener(e->{
                    AlertUtil alertUtil = new AlertUtil(GoodsActivity.this,R.layout.dialog_exchange,true) {
                        @Override
                        public void setView(View view) {

                            view.findViewById(R.id.define).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    // 点击进行兑换操作
                                    String address = ((TextView)view.findViewById(R.id.address)).getText().toString();
                                    String phone = ((TextView)view.findViewById(R.id.phone)).getText().toString();
                                    if(DataTool.isBlank(address)||DataTool.isBlank(phone)){
                                        Toast.makeText(getApplicationContext(),"请填写关键信息",Toast.LENGTH_SHORT).show();
                                        return ;
                                    }
                                    service.exchange(obj.getId(),user.getId(),phone,address);
                                    dismiss();
                                }
                            });
                            view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dismiss();
                                }
                            });
                        }
                    };
                    alertUtil.show();
                });
            }
        };
        //设置垂直的线性布局管理器，Orientation --> VERTICAL:垂直 HORIZONTAL:水平
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        //StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        //添加分割线
//        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();
        this.mSwipeRefresh.setColorSchemeColors(Color.RED,Color.GREEN,Color.BLUE);
        this.mSwipeRefresh.setOnRefreshListener(mController);
        this.recyclerView.addOnScrollListener(mController);
        initHandler();
    }
    @Override
    protected void onStart() {
        super.onStart();
        myAdapter.clear();
        pageOn = 1;
        service.getGoodsPage(pageOn,user.getId());
    }

    private void initHandler() {
        viewModel.getGoods().observe(this,e->{
            String result = e.getString("result");
            String detail = e.getString("detail");
            if("SUCCESS".equals(result)){
                JSONArray list = e.getJSONArray("list");
                if (list != null && list.size() > 0) {
                    myAdapter.addAll(list.toJavaList(Goods.class));
                }else{
                }
                if(myAdapter.getmData().size() == 0){
                    binding.hint.setVisibility(View.VISIBLE);
                    Toast.makeText(getApplicationContext(), "空空如也~", Toast.LENGTH_SHORT).show();
                }else{
                    binding.hint.setVisibility(View.GONE);
                }
            }else{
                Toast.makeText(getApplicationContext(),detail,Toast.LENGTH_SHORT).show();
            }
        });
        viewModel.getExchangeResult().observe(this,e->{
            String result = e.getString("result");
            String detail = e.getString("detail");
            if("SUCCESS".equals(result)){
                pageOn = 1;
                service.getGoodsPage(pageOn,user.getId());
            }else{
                Toast.makeText(getApplicationContext(),detail,Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void refresh() {
        myAdapter.clear();
        pageOn = 1;
        service.getGoodsPage(pageOn,user.getId());
        mSwipeRefresh.setRefreshing(false);
        mController.setLoadDataStatus(false);
    }

    @Override
    public void loadMore() {
        //加载更多的接口回调
        pd = new ProgressDialog(this);
        pd.show();
        mSwipeRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                service.getGoodsPage(++pageOn,user.getId());
                //设置数据加载结束的监听状态
                mController.setLoadDataStatus(false);
                pd.dismiss();
            }
        },2000);
    }
}